package main

import (
	"encoding/base64"
	"encoding/json"
	"io"
	"net/http"
	"strings"

	// "encoding/json"
	"fmt"

	// "github.com/asters1/tools"
	"github.com/gin-gonic/gin"
)

type Opt_m struct {
	method  string
	headers map[string]string
	url     string
	data    map[string]string
}
type Res_data struct {
	headers map[string][]string
	content string
}

func p_log(name string, content any) {

	fmt.Println("======" + name + "======")
	fmt.Println(content)
	// fmt.Println("======" + name + "======")

}

func request(URL string, METHOD string, HEADER map[string]string, Data map[string]string) Res_data {
	client := &http.Client{}
	fmt.Println(HEADER)
	p_log("URL", URL)
	p_log("METHOD", METHOD)
	p_log("HEADERS", HEADER)
	p_log("DATA", Data)

	// 转换方法为大写
	METHOD = strings.ToUpper(METHOD)

	// 处理请求数据
	FormatData := ""
	for i, j := range Data {
		FormatData = FormatData + i + "=" + j + "&"
	}
	if FormatData != "" {
		FormatData = FormatData[:len(FormatData)-1]
	}

	// 创建请求（检查错误）
	requset, err := http.NewRequest(
		METHOD,
		URL,
		strings.NewReader(FormatData),
	)
	if err != nil {
		fmt.Println("创建请求失败:", err)
		return Res_data{}
	}

	// 设置默认Content-Type
	if METHOD == http.MethodPost && requset.Header.Get("Content-Type") == "" {
		requset.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	}

	// 设置User-Agent
	requset.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.71 Safari/537.36")

	// 添加自定义header
	for i, j := range HEADER {
		requset.Header.Set(i, j)
	}

	// 发送请求（检查错误）
	resp, err := client.Do(requset)
	if err != nil {
		fmt.Println("请求失败:", err)
		return Res_data{}
	}
	defer resp.Body.Close()

	// 读取响应体（检查错误）
	body_bit, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("读取响应失败:", err)
		return Res_data{}
	}

	// 构造返回数据
	context := string(body_bit)
	// p_log("Body", context)
	d := Res_data{
		headers: resp.Header,
		content: context,
	}

	return d
}

func res_to_json(r_data Res_data) string {

	res_headers := r_data.headers
	context := r_data.content

	// 将头部转换为字符串
	headersStr := ""
	for key, values := range res_headers {
		for _, value := range values {
			value = strings.ReplaceAll(value, `"`, `\"`)
			headersStr += fmt.Sprintf("\"%s\": \"%s\",", key, value)
		}
	}
	headersStr = headersStr[:len(headersStr)-1]

	context = strings.ReplaceAll(context, `\`, `\\`)
	context = strings.ReplaceAll(context, `"`, `\"`)
	context = strings.ReplaceAll(context, "\n", "\\n")

	r := make(map[string]string)
	r["headers"] = "{" + headersStr + "}"
	r_str := `{
	  "headers":{` + headersStr + `},
    "content":"` + context + `"
  }`

	return r_str
}

func main() {
	fmt.Println("======")
	// 创建一个默认的路由引擎
	r := gin.Default()
	// GET：请求方式；/hello：请求的路径
	// 当客户端以GET方法请求/hello路径时，会执行后 面的匿名函数
	r.GET("/*a", func(c *gin.Context) {
		txt := c.Param("a")[1:]
		fmt.Println(txt)
		c.String(200, txt)

	})
	r.POST("/", func(c *gin.Context) {
		// fmt.Println(c.Request.Header)
		// fmt.Println(c.Request.Body)
		// defer c.Request.Body.Close()
		b, _ := c.GetRawData()
		fmt.Println("收到的结果为" + string(b))
		c.String(200, string(b))

	})
	r.POST("/post", func(c *gin.Context) {
		// c.String(200, "jjjj")
		b, _ := c.GetRawData() // 从c.Request.Body读取请求数据
		// 定义map或结构体
		var m map[string]interface{}
		// 反序列化
		_ = json.Unmarshal(b, &m)
		o := m_Parse(m)
		// fmt.Println(o)

		// fmt.Println("====")
		// fmt.Println(o.url)
		// fmt.Println(o.method)
		// fmt.Println(o.headers)
		// fmt.Println(o.data)
		// fmt.Println("====")
		result := request(o.url, o.method, o.headers, o.data)
		// fmt.Println(result)
		res := res_to_json(result)
		// fmt.Println("===res=====")
		// fmt.Println(res)
		// fmt.Println("=======")
		p_log("res", res)

		c.String(200, res)

	})
	// 启动HTTP服务，默认在0.0.0.0:8080启动服务
	r.Run()
}
func base64_to_str(basr64_str string) string {
	basr64_str = strings.ReplaceAll(basr64_str, "*", "=")
	b, e := base64.StdEncoding.DecodeString(basr64_str)
	if e != nil {
		return ""
	}
	return string(b)

}
func m_Parse(result map[string]interface{}) Opt_m {
	// fmt.Print("获得的数据--->")
	// fmt.Println(result)
	o := Opt_m{}
	// 处理headers
	headers := make(map[string]string)
	data := make(map[string]string)
	if h, ok := result["headers"].(map[string]interface{}); ok {
		for k, v := range h {
			headers[k] = fmt.Sprint(v) // 强制转为字符串
		}
	}
	if h, ok := result["data"].(map[string]interface{}); ok {
		for k, v := range h {
			data[k] = fmt.Sprint(v) // 强制转为字符串
		}
	}
	o.url = fmt.Sprint(result["url"])

	o.method = fmt.Sprint(result["method"])
	o.headers = headers
	o.data = data
	return o
}
